package com.arong.biBackend.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.arong.biBackend.common.ErrorCode;
import com.arong.biBackend.exception.BusinessException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class ExcelUtils {
    /**
     * 格式有要求
     * 第一列为列名，
     * 第二列为数据类型 只能填写 “字符串” 或者 “数字” 填写其他或者不填写一律按“字符串”处理
     * 接下来为数据
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "系统处理错误" + e);
        }
        StringBuilder stringBuilder = new StringBuilder();

//        LinkedHashMap<Integer, String> headMap = (LinkedHashMap)list.get(0);
//        // 读取表头数据（属性）
//        List<String> headerList = headMap.values().stream()
//                .filter(ObjectUtils::isNotEmpty)
//                .collect(Collectors.toList());
//        stringBuilder.append(StringUtils.join(headerList, ",")).append("\n");
        // 依次读取每一列的数据
        for(int i = 0; i < list.size(); i++) {
            LinkedHashMap<Integer, String> dataMap = (LinkedHashMap)list.get(i);
            // 读取表头数据（属性）
            List<String> dataList = dataMap.values().stream()
                    .filter(ObjectUtils::isNotEmpty)
                    .collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList, ",")).append("\n");
        }
        return stringBuilder.toString();
    }

}
